<?php
/**
 * Created by 胡祥能 on 2018/4/16.
 *  email：huxiangneng@jiuletech.com
 */

namespace App\Http\Controllers\Admin;


use App\Helpers\Api\ApiResponse;
use App\Models\Sidebar;
use App\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Log;
use Illuminate\Support\Facades\Cache;

class SidebarController extends DefaultController
{

    use ApiResponse;

    public function index(Request $request)
    {
        $sidebars = Sidebar::get();

        $grouped = $sidebars->keyBy('id');
        $grouped = $grouped->toArray();
        foreach ($grouped as &$val) {
            $val['roles'] = Sidebar::find($val['id'])->roles()->select('display_name')->get()->toArray();
        }

        $result = Sidebar::generateTree($grouped);
        Sidebar::arraySortRecursive($result);

        $roles = Role::all();
        return view('admin.system.menu', ['sidebars' => $result, 'roles'=>$roles]);
    }

    public function add(Request $request){
         $validator = Validator::make($request->all(), [
              'name' => 'bail|required|max:50',
              'pid' => 'bail|required',
         ]);

        try {
            DB::beginTransaction();
            $sidebar = new Sidebar();
            $pid = $request->input('pid');
            $name = $request->input('name');
            $url = $request->input('url');
            $icon = $request->input('icon');
            $sort = $request->input('sort');

            $sidebar->name = $name;
            $sidebar->pid = $pid;
            $sidebar->url = $url;
            $sidebar->icon = $icon;
            $sidebar->sort = $sort;
            $sidebar->save();

            $assign_roles = $request->input('assign-roles');//角色对应关系先不处理
            if(is_array($assign_roles) && $assign_roles){
                $inserts = [];
                foreach ($assign_roles as $item) {
                    array_push($inserts, ['sidebar_id'=>$sidebar->id, 'role_id'=>$item]);
                }
                DB::table(Sidebar::SIDEBAR_ROLE)->insert($inserts);
            }

            DB::commit();
            Sidebar::deleteSidebarCache();//删除缓存
            return $this->successView('', '/menus');

        } catch (\Exception $exception) {
            Log::info($exception->getMessage() . $exception->getLine());
            DB::rollBack();//出异常，回滚
            return $this->failView('出了一点小问题', '/menus');
        }
    }

    public function update(Request $request){
        $id = $request->input('id');
        if (empty($id)) {
            return $this->failView('缺少参数', '/menus');
        }

        if($request->method() == "POST"){

            $validator = Validator::make($request->all(), [
                'name' => 'bail|required|max:50',
                'pid' => 'bail|required',
            ]);
            try {
                DB::beginTransaction();
                $sidebar = Sidebar::find($id);
                $pid = $request->input('pid');
                $name = $request->input('name');
                $url = $request->input('url');
                $icon = $request->input('icon');
                $sort = $request->input('sort');

                $sidebar->name = $name;
                $sidebar->pid = $pid;
                $sidebar->url = $url;
                $sidebar->icon = $icon;
                $sidebar->sort = $sort;
                $sidebar->save();

                $assign_roles = $request->input('assign-roles')?:[];//角色对应关系先不处理
                $sidebarRoles = $sidebar->roles()->get()->toArray();
                $sidebarRolesIdArr = array_column($sidebarRoles, 'id');
                $diff1 = array_diff($sidebarRolesIdArr, $assign_roles);//需要删除的角色id
                $diff2 = array_diff($assign_roles, $sidebarRolesIdArr);//需要增加的角色id
                if($diff1){
                    foreach ($diff1 as $v){
                        DB::table(Sidebar::SIDEBAR_ROLE)->where('sidebar_id', $id)->where('role_id', (int)$v)->delete();
                    }
                }

                if($diff2){
                    foreach ($diff2 as $item){
                        DB::table(Sidebar::SIDEBAR_ROLE)->insert([
                            'sidebar_id'=> $id,
                            'role_id'=> (int)$item
                        ]);
                    }
                }

                DB::commit();
                Sidebar::deleteSidebarCache();//删除缓存
                return $this->successView('', '/menus');

            } catch (\Exception $exception) {
                Log::info($exception->getMessage() . $exception->getLine());
                DB::rollBack();//出异常，回滚
                return $this->failView('出了一点小问题', '/menus');
            }
        }else{
            $sidebar = Sidebar::find($id);

            $sidebars = Sidebar::get();
            $grouped = $sidebars->keyBy('id');
            $grouped = $grouped->toArray();

            foreach ($grouped as $key=>$value) {
                if($value['id'] == $id){
                    unset($grouped[$key]);
                }
            }
            $result = Sidebar::generateTree($grouped, $sidebar->pid);
            Sidebar::arraySortRecursive($result);

            $roles = Role::all();
            $assign_roles = $sidebar->roles()->get()->toArray();
            $assign_roles_id = array_column($assign_roles, 'id');
            foreach ($roles as &$role) {
                if (in_array($role->id, $assign_roles_id)) {
                    $role->selectd = true;
                }else{
                    $role->selectd = false;
                }
            }
            return view('admin.system.menu-update', ['sidebar'=>$sidebar, 'sidebars' => $result, 'roles'=>$roles]);
        }
    }

    public function delete(Request $request){
        $id = $request->input('id');
        if (empty($id)) {
            return $this->json(1001);
        }

        try {
            DB::beginTransaction();
            $sidebar = Sidebar::find($id);
            $res = $sidebar->delete();

            Sidebar::where('pid', $id)->delete();

            if($res){
                DB::commit();

                //验证和角色的关联是否与之删除
                DB::table(Sidebar::SIDEBAR_ROLE)->where('sidebar_id', $id)->delete();
                Sidebar::deleteSidebarCache();//删除缓存
                return $this->json(200);
            }else{
                DB::rollBack();
                return $this->json(1002);
            }

        } catch (Exception $exception) {
            Log::info($exception->getMessage() . $exception->getLine());
            DB::rollBack();//出异常，回滚
            return $this->failView('出了一点小问题', '/menus');
        }
    }
}
